package cn.gzjp.modules.wx.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.modules.wx.entity.WxCorp;
import cn.gzjp.modules.wx.service.WxCorpService;

/**
 * 企业号信息Controller
 * @author zengcp
 * @version 2017-09-18
 */
@Controller
@RequestMapping(value = "${adminPath}/wx/wxCorp")
public class WxCorpController extends BaseController {

	@Autowired
	private WxCorpService wxCorpService;
	
	
	/**
	 * 企业号信息列表页面
	 */
	@RequiresPermissions("wx:wxCorp:list")
	@RequestMapping(value = {"list", ""})
	public String list(WxCorp wxCorp, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WxCorp> page = wxCorpService.findPage(new Page<WxCorp>(request, response), wxCorp); 
		model.addAttribute("page", page);
		return "modules/wx/wxCorpList";
	}

	/**
	 * 查看，增加，编辑企业号信息表单页面
	 */
	@RequiresPermissions(value={"wx:wxCorp:view","wx:wxCorp:add","wx:wxCorp:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxCorp wxCorp, Model model) {
		model.addAttribute("wxCorp", wxCorp);
		return "modules/wx/wxCorpForm";
	}

	/**
	 * 保存企业号信息
	 */
	@RequiresPermissions(value={"wx:wxCorp:add","wx:wxCorp:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxCorp wxCorp, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, wxCorp)){
			return form(wxCorp, model);
		}
		if(!wxCorp.getIsNewRecord()){//编辑表单保存
			WxCorp t = wxCorpService.get(wxCorp.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(wxCorp, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			wxCorpService.save(t);//保存
		}else{//新增表单保存
			wxCorpService.save(wxCorp,wxCorp.getId());//保存
		}
		addMessage(redirectAttributes, "保存企业号信息成功");
		return redirect("/wx/wxCorp/?repage");
	}
	
	
	
	
	@ModelAttribute
	public WxCorp get(@RequestParam(required=false) String id) {
		WxCorp entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wxCorpService.get(id);
		}
		if (entity == null){
			entity = new WxCorp();
		}
		return entity;
	}
	

}